﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BookStore.Models;
using System.Data;
namespace BookStore.Controllers
{
    [HandleError]
    public class BookController : Controller
    {
        private Random random = new Random();
        private string GenerateRandomCode()
        {
            string s = "";
            for (int i = 0; i < 6; i++)
                s = String.Concat(s, this.random.Next(10).ToString());
            return s;
        }

        public ActionResult Detail()
        {
            BookModel tbBook = new BookModel();
            CategoriesModel tbCategories = new CategoriesModel();
            FavoriteModel tbFavorite = new FavoriteModel();
            CommentModel tbComment = new CommentModel();

            int id = Convert.ToInt32(this.Request.QueryString["id"]);
            string[] result = new string[15];
            result = tbBook.getBookbyID(id);
            if (result[0] == null) return RedirectToAction("Index", "Home");
            ViewData["book_code"] = result[0];
            ViewData["book_name"] = result[1];
            ViewData["author_name"] = result[2];
            ViewData["price_buy"] = result[3];
            ViewData["price_rent"] = result[4];
            ViewData["image_url"] = result[7];
            ViewData["updated_date"] = result[8];
            ViewData["short_description"] = result[9];
            ViewData["long_description"] = result[10];

            ViewData["book_id"] = id;
            ViewData["num_like"] = tbFavorite.getFavorite(id);

            ViewData["resultRelative"] = tbBook.getBookRelativeByID(Convert.ToInt32(result[11]),id);
            ViewData["category_name"] = tbCategories.getCategoryByID(Convert.ToInt32(result[11]));
            ViewData["category_id"] = Convert.ToInt32(result[11]);

            this.Session["CaptchaImageText"] = GenerateRandomCode();
            int countComment = tbComment.countCommentbyID(id);
            int page = Convert.ToInt32(this.Request.QueryString["page"]);
            if (page == 0) page = 1;
            int limit = 5;
            Pagination pagination = new Pagination("/book/jsonPage?id=" + id + "&page=", countComment, limit, page);

            string[][] resultComment = tbComment.getCommentbyID(id, page, limit);
            ViewData["resultComment"] = resultComment;
            ViewData["pagination"] = pagination.renderJson();

            return View();
        }

        public ActionResult Category()
        {
            BookModel tbBook = new BookModel();
            CategoriesModel tbCategories = new CategoriesModel();

            int id = Convert.ToInt32(this.Request.QueryString["id"]);
            ViewData["category_name"] = tbCategories.getCategoryByID(id);
            if (ViewData["category_name"] == "") return RedirectToAction("Index", "Home");

            int countBook = tbBook.countBookbyCateID(id);
            int page = Convert.ToInt32(this.Request.QueryString["page"]);
            if(page == 0) page = 1;
            int limit = 12;
            Pagination pagination = new Pagination("/book/category?id=" + id + "&page=", countBook, limit, page);

            string[][] result = tbBook.getBookByCateID(id, page, limit);
            ViewData["resultBooks"] = result;
            ViewData["pagination"] = pagination.render();

            return View();
        }

        public ActionResult Search()
        {
            CategoriesModel tbCategory = new CategoriesModel();
            BookModel tbBook = new BookModel();

            DataTable result = new DataTable();
            int i = 0;
            try
            {
                result = tbCategory.getAllCategories();
                if (result != null && result.Rows.Count > 0)
                {
                    string[][] category = new string[result.Rows.Count][];
                    i = 0;
                    foreach (DataRow row in result.Rows)
                    {
                        category[i] = new string[2];
                        category[i][0] = row["category_id"].ToString();
                        category[i][1] = row["category_name"].ToString();
                        i++;
                    }
                    ViewData["category"] = category;
                }
                else
                {
                    ViewData["category"] = null;
                }
            }
            catch (SystemException ex)
            {
                ViewData["category"] = null;
            }

            if (this.Request.QueryString["title"] != null)
            {
                ViewData["category_id"] = this.Request.QueryString["category"] == null ? "-1" : this.Request.QueryString["category"];
                ViewData["title"] = this.Request.QueryString["title"] == null ? "" : this.Request.QueryString["title"];
                ViewData["content"] = this.Request.QueryString["content"] == null ? "" : this.Request.QueryString["content"];
                ViewData["option"] = this.Request.QueryString["option"] == null ? "1" : this.Request.QueryString["option"];
                ViewData["price_from"] = this.Request.QueryString["price_from"] == null ? "" : this.Request.QueryString["price_from"];
                ViewData["price_to"] = this.Request.QueryString["price_to"] == null ? "" : this.Request.QueryString["price_to"];
                ViewData["price_rent_from"] = this.Request.QueryString["price_rent_from"] == null ? "" : this.Request.QueryString["price_rent_from"];
                ViewData["price_rent_to"] = this.Request.QueryString["price_rent_to"] == null ? "" : this.Request.QueryString["price_rent_to"];
                try
                {
                    int countBook = tbBook.countBookbySearch(
                       ViewData["title"].ToString(),
                       ViewData["content"].ToString(),
                       Convert.ToInt32(ViewData["option"]),
                       Convert.ToInt32(ViewData["category_id"]),
                       Convert.ToInt32(ViewData["price_from"] == "" ? "0" : ViewData["price_from"]),
                       Convert.ToInt32(ViewData["price_to"] == "" ? "0" : ViewData["price_to"]),
                       Convert.ToInt32(ViewData["price_rent_from"] == "" ? "0" : ViewData["price_rent_from"]),
                       Convert.ToInt32(ViewData["price_rent_to"] == "" ? "0" : ViewData["price_rent_to"]));

                    ViewData["countBook"] = countBook;
                    int page = Convert.ToInt32(this.Request.QueryString["page"]);
                    if (page == 0) page = 1;
                    int limit = 9;

                    string paramater = this.Request.QueryString.ToString();
                    if (this.Request.QueryString["page"] != null)
                    {
                        string page_str = "&page=" + this.Request.QueryString["page"].ToString();
                        paramater = paramater.Trim(page_str.ToCharArray());
                    }
                    Pagination pagination = new Pagination("/book/search?" + paramater + "&page=", countBook, limit, page);

                    string[][] resultSearch = tbBook.getBookbySearch(
                        ViewData["title"].ToString(),
                        ViewData["content"].ToString(),
                        Convert.ToInt32(ViewData["option"]),
                        Convert.ToInt32(ViewData["category_id"]),
                        Convert.ToInt32(ViewData["price_from"] == "" ? "0" : ViewData["price_from"]),
                        Convert.ToInt32(ViewData["price_to"] == "" ? "0" : ViewData["price_to"]),
                        Convert.ToInt32(ViewData["price_rent_from"] == "" ? "0" : ViewData["price_rent_from"]),
                        Convert.ToInt32(ViewData["price_rent_to"] == "" ? "0" : ViewData["price_rent_to"]),
                        page, limit);

                    ViewData["resultSearch"] = resultSearch;
                    ViewData["pagination"] = pagination.render();
                }
                catch (SystemException ex)
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ViewData["init"] = "noinit";
                ViewData["resultSearch"] = new string[1][];
            }

            return View();
        }

        public ActionResult JsonAddLike()
        {
            if (this.Request.QueryString["id"] != null)
            {
                int user_id = -1;
                if (this.Session["Session_User"] != null)
                    user_id = Convert.ToInt32(this.Session["Session_User"]);
                if (user_id == -1) return Content("-3");
                int book_id = Convert.ToInt32(this.Request.QueryString["id"]);
                FavoriteModel tbFavorite = new FavoriteModel();
                return Content(tbFavorite.insertFavorite(user_id, book_id).ToString());
            }
            return Content("-2");
        }

        public ActionResult JsonAddComment()
        {
            if (this.Request.QueryString["id"] != null)
            {
                int user_id = -1;
                if (this.Session["Session_User"] != null)
                    user_id = Convert.ToInt32(this.Session["Session_User"]);
                if (user_id == -1) return Content("-3");
                int book_id = Convert.ToInt32(this.Request.QueryString["id"]);
                string comment = this.Request.QueryString["comment"];

                CommentModel tbComment = new CommentModel();
                int result = tbComment.insertComment(user_id, book_id,Server.HtmlEncode(comment));
                if (result == 1)
                {
                    int id = Convert.ToInt32(this.Request.QueryString["id"]);
                    string html = this.getListComment(id, 1);
                    return Content(html);
                }
                else return Content(result.ToString());
            }
            return Content("-2");
        }

        public ActionResult JsonPage()
        {
            if (this.Request.QueryString["id"] != null)
            {
                int id = Convert.ToInt32(this.Request.QueryString["id"]);
                int page = Convert.ToInt32(this.Request.QueryString["page"]);
                string html = this.getListComment(id,page);
                return Content(html);
            }
            return Content("-2");
        }

        private string getListComment(int id,int page)
        {
            CommentModel tbComment = new CommentModel();
            int countComment = tbComment.countCommentbyID(id);
            if (page == 0) page = 1;
            int limit = 5;
            Pagination pagination = new Pagination("/book/jsonPage?id=" + id + "&page=", countComment, limit, page);
            string[][] resultComment = tbComment.getCommentbyID(id, page, limit);

            string html = "";
            if (resultComment[0] != null)
            {
                foreach (string[] row in resultComment)
                {
                    if (row == null) break;
                    html += "<div class='content'><b>" + row[2] + "</b> | " + row[0] + "<br>";
                    html += row[1];
                    html += "</div><br>";
                }
            }
            else
                html += " <br />&nbsp;&nbsp;&nbsp;&nbsp;Không có bình luận nào !    ";
            html += "  <div class='pagination'>";
            html += pagination.renderJson();
            html += "  </div>";

            return html;
        }
        public ActionResult FavoriteBook()
        {
            BookModel tbBook = new BookModel();
            CategoriesModel tbCategories = new CategoriesModel();
            if (Session["Session_User"] != null)
            {
                int id = Convert.ToInt32(Session["Session_User"]);

                int countBook = tbBook.getCountFavoriteBookByUserID(id); ;
                int page = Convert.ToInt32(this.Request.QueryString["page"]);
                if (page == 0) page = 1;
                int limit = 12;
                Pagination pagination = new Pagination("/book/favoritebook?id=" + id + "&page=", countBook, limit, page);

                string[][] result = tbBook.getFavoriteBookByUserID(id, page, limit);
                ViewData["resultBooks"] = result;
                ViewData["pagination"] = pagination.render();
            }
            else Response.Redirect("/home/index");
            return View();
        }
    }
}
